package com.rain.rainspringboot3.encryption.mapper;

import com.rain.rainspringboot3.encryption.entity.User;
import com.rain.rainspringboot3.encryption.entity.UserDTO;
import com.rain.rainspringboot3.encryption.entity.UserVO;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;

@Mapper(componentModel = "spring")
public interface UserDTOMapper {

    @Mapping(target = "phoneSensitiveId", source = "phone", qualifiedByName = "objectToLong")
    @Mapping(target = "idCardSensitiveId", source = "idCard", qualifiedByName = "objectToLong")
    @Mapping(target = "emailSensitiveId", source = "email", qualifiedByName = "objectToLong")
    @Mapping(target = "createTime", ignore = true)
    User toUserVO(UserDTO userDTO);

    @Mapping(target = "phone", source = "phoneSensitiveId", qualifiedByName = "fromLong")
    @Mapping(target = "idCard", source = "idCardSensitiveId", qualifiedByName = "fromLong")
    @Mapping(target = "email", source = "emailSensitiveId", qualifiedByName = "fromLong")
    UserVO toUserVO(User user);


    @Named("fromLong")
    default String fromLong(Long value) {
        return value == null ? null : value.toString();
    }
    @Named("objectToLong")
    default Long objectToLong(Object value) {
        if (value == null) {
            return null;
        }
        if (value instanceof Long) {
            return (Long) value;
        }
        if (value instanceof String) {
            try {
                return Long.parseLong((String) value);
            } catch (NumberFormatException e) {
                return null;
            }
        }
        if (value instanceof Number) {
            return ((Number) value).longValue();
        }
        return null;
    }

}